package logic

import (
	"context"
	"fmt"
	"models"
	"strconv"

	"shop_srv/internal/svc"
	"shop_srv/shop_srv"

	"github.com/zeromicro/go-zero/core/logx"
)

type CarListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCarListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CarListLogic {
	return &CarListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CarListLogic) CarList(in *shop_srv.CarListRequest) (*shop_srv.CarListResponse, error) {
	// todo: add your logic here and delete this line
	var key = fmt.Sprintf("card_%d:*", in.UserId)
	keys, _ := models.Rdb.Keys(models.Ctx, key).Result()
	var goods []*shop_srv.CarGoods
	for _, s := range keys {
		result, err := models.Rdb.HGetAll(models.Ctx, s).Result()
		if err != nil {
			return nil, err
		}
		price, _ := strconv.ParseFloat(result["price"], 64)
		number, _ := strconv.ParseInt(result["number"], 10, 64)
		var gs = shop_srv.CarGoods{
			Name:  result["name"],
			Price: float32(price),
			Stock: number,
		}
		goods = append(goods, &gs)
	}
	return &shop_srv.CarListResponse{
		Goods: goods,
	}, nil
}
